<template>
  <div v-loading="loading" :element-loading-text="loadingText">
    <div class="bread-box but20">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item class="btn-green" style=" color: #3DC094;" @click.native="goBack">成品套房方案管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{ formData.id ? (flag === 'edit' ? '编辑' : '详情') : '新增' }}</el-breadcrumb-item>
      </el-breadcrumb>
      <div>
        <el-button size="mini" @click="goBack">返回</el-button>
      </div>
    </div>
    <div>
      <div class="qup-title-box">
        <span class="border" /><span>产品方案</span>
      </div>
      <div style="margin-bottom: 10px">
        <el-button v-if="!isEditForm && flag !== 'detail'" type="primary" size="mini" @click="handleEditForm">编辑</el-button>
        <div v-if="isEditForm">
          <el-button type="primary" size="mini" @click="handleSaveInfo">保存</el-button>
          <el-button size="mini" @click="cancel">取消</el-button>
        </div>
      </div>
      <el-form ref="refForm" class="financeForm" :rules="rules" :model="formData" size="mini" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属方案:" size="mini" prop="configPlan">
              <span>{{ formData.programName }}</span>
              <!-- <input-with-dialog
                v-else
                v-model="formData.configPlan"
                :props="{label:'programName',value:'id'}"
                :config="planConfig"
                @change="planChange"
              /> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属空间:" prop="configSpace">
              <span>{{ formData.spaceName }}</span>
              <!-- <input-with-dialog
                v-else
                v-model="formData.configSpace"
                :props="{label:'spaceName',value:'id'}"
                :config="spaceConfig"
                @change="spaceChange"
              /> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="建议上样面积:" prop="adviceSampleArea">
              <span v-if="flag === 'detail' || !isEditForm">{{ formData.adviceSampleArea }}</span>
              <el-input v-else v-model="formData.adviceSampleArea" placeholder="请输入建议上样面积" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="空间说明:" prop="spaceDesc">
              <span v-if="flag === 'detail' || !isEditForm">{{ formData.spaceDesc }}</span>
              <el-input v-else v-model="formData.spaceDesc" placeholder="请输入空间说明" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属区域:" size="mini" prop="areaName">
              <span>{{ formData.areaName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="区域说明:" size="mini" prop="areaDesc">
              <span>{{ formData.areaDesc }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <div class="qup-title-box">
        <span class="border" /><span>方案配置</span>
      </div>
      <search-form
        :search-config="searchConfig"
        :label-width="150"
        style="margin:10px 0"
        @clear="clearSearch"
        @search="handleSearch"
      />
      <div v-if="flag !== 'detail'" class="btn-group">
        <el-button v-if="!isEditTable" type="primary" size="mini" @click="addSerise">新增方案明细</el-button>
        <el-button v-if="showPageFlag" type="primary" size="mini" @click="editSerise">编辑方案明细</el-button>
        <!-- <el-button v-if="showPageFlag" type="primary" size="mini" @click="handleImport">导入</el-button> -->
        <!-- <el-button v-if="showPageFlag" type="primary" size="mini" @click="handleExport">导出</el-button> -->
        <el-button v-if="!isEditTable" type="primary" size="mini" @click="handleDel">删除</el-button>
        <el-button v-if="showPageFlag" type="primary" size="mini" @click="handleChangeStatus(1)">启用</el-button>
        <el-button v-if="showPageFlag" type="primary" size="mini" @click="handleChangeStatus(0)">停用</el-button>
        <el-button v-if="!showPageFlag && isEditTable" type="primary" size="mini" @click="saveEditRow">保存编辑</el-button>
        <el-button v-if="!showPageFlag && !isEditTable" type="primary" size="mini" @click="saveNewRow">保存</el-button>
        <el-button v-if="!showPageFlag" type="primary" size="mini" @click="cancelEdit">取消</el-button>
      </div>
      <div>
        <el-table
          ref="refTable"
          v-loading="tableLoading"
          element-loading-text="加载中"
          :data="tableData"
          border
          highlight-current-row
          max-height="400"
          :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
          style="width: 100%; margin-top: 20px"
          @selection-change="selectionChangeHandle"
        >
          <el-table-column v-if="flag !== 'detail'" type="selection" width="55" :selectable="selectable" />
          <el-table-column prop="styleName" label="所属专区" min-width="100" show-overflow-tooltip>
            <template slot="header">
              <span style="color: red">*</span>所属专区
            </template>
          </el-table-column>
          <el-table-column prop="adviceArea" label="建议面积" min-width="120" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="flag === 'detail' || !scope.row.editFlag">{{ scope.row.adviceArea }}</span>
              <el-input v-if="scope.row.editFlag" v-model="scope.row.adviceArea" size="mini" placeholder="请输入建议上样最低面积" />
            </template>
          </el-table-column>
          <el-table-column prop="seriesName" label="产品系列" min-width="80" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="flag === 'detail' || !scope.row.addFlag">{{ scope.row.seriesName }}</span>
              <input-with-dialog
                v-else
                v-model="scope.row.series"
                :props="{label:'seriesName',value:'seriesCode'}"
                :multiple="true"
                :config="scope.row.seriesConfig"
                @change="seriesChange(scope.row, scope.$index)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="seriesDesc" label="系列说明" min-width="100" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="flag === 'detail' || !scope.row.editFlag">{{ scope.row.seriesDesc }}</span>
              <el-input v-if="scope.row.editFlag" v-model="scope.row.seriesDesc" size="mini" placeholder="请输入系列说明" />
            </template>
          </el-table-column>
          <el-table-column prop="assortCustomizedSeriesName" label="配套定制系列" min-width="80" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="flag === 'detail' || !scope.row.editFlag">{{ scope.row.assortCustomizedSeriesName }}</span>
              <input-with-dialog
                v-else
                v-model="scope.row.customizedSeries"
                :multiple="true"
                :props="{label:'seriesName',value:'id'}"
                :config="scope.row.customizedSeriesConfig"
                @change="customizedSeriesChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="assortCupboardSeriesName" label="配套橱柜系列" min-width="80" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="flag === 'detail' || !scope.row.editFlag">{{ scope.row.assortCupboardSeriesName }}</span>
              <input-with-dialog
                v-else
                v-model="scope.row.cupboardSeries"
                :multiple="true"
                :props="{label:'seriesName',value:'id'}"
                :config="scope.row.cupboardSeriesConfig"
                @change="cupboardSeriesChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="isMustUp" label="是否必上" min-width="100" show-overflow-tooltip>
            <template slot="header">
              <span style="color: red">*</span>是否必上
            </template>
            <template slot-scope="scope">
              <span v-if="flag === 'detail' || !scope.row.editFlag">{{ formaterData(booleansList, scope.row.isMustUp) }}</span>
              <el-select v-if="scope.row.editFlag" v-model="scope.row.isMustUp" size="mini" placeholder="请选择是否必上" style="width:100%">
                <el-option v-for="item in booleansList" :key="item.dictCode" :label="item.dictName" :value="item.dictCode" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="enable" label="启用状态" min-width="100" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ formaterData(enableList, scope.row.enable) }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-box">
          <div v-if="showPageFlag" class="pagination-container">
            <el-pagination
              :current-page.sync="tableInfo.currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="10"
              layout="sizes, prev, pager, next, slot"
              :total="allTotal === 0 ? tableInfo.total : allTotal"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            >
              <span class="el-pagination__jump">前往
                <el-input-number
                  v-model="jumpPage"
                  :controls="false"
                  :min="1"
                  @blur="showEnter"
                  @keyup.enter.native="showEnter"
                />页</span>
            </el-pagination>
            <div v-show="tableInfo.total <= tableInfo.rows" class="pagination-info">当前显示
              <span>{{ handlePageRange(tableInfo.rows, tableInfo.currentPage) }}</span>，共
              <span class="total"> {{ tableData.length }} </span> 条记录
            </div>
            <div v-show="tableInfo.total > tableInfo.rows" class="pagination-info">当前显示
              <span>{{ handlePageRange(tableInfo.rows, tableInfo.currentPage) }}</span>，共
              <span :class="[allTotal === 0 && tableInfo.total !== 0 ? 'total next-page': 'total']" @click="newEnter"> {{ (allTotal === 0 && tableInfo.total !== 0) ? ((tableInfo.total-1) +'+'): allTotal }}  </span> 条记录
            </div>
          </div>
        </div>
      </div>
      <!-- <div v-if="flag === 'detail'" class="foot-info">
        <el-form ref="refForm" class="financeForm" :model="formData" size="mini" label-width="90px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="创建人:" size="mini" prop="createBy">
                <span>{{ formData.createBy }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="创建时间:" size="mini" prop="createTime">
                <span>{{ formData.createTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="修改人:" size="mini" prop="lastUpdateBy">
                <span>{{ formData.lastUpdateBy }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="修改时间:" size="mini" prop="lastUpdateTime">
                <span>{{ formData.lastUpdateTime }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div> -->
      <div>
        <import-files v-if="importVisible" title="导入" :visible.sync="importVisible" :config="fileImportConfig" @success="handleImportSuccess" />
        <export-files v-if="exportVisible" title="导出" :config="exportConfig" :visible.sync="exportVisible" @success="handleExportSuccess" />
      </div>
      <style-dialog v-if="showSeriesDlg" ref="tipDlg" :visible.sync="showSeriesDlg" :other-filter="otherFilters" @addSeries="pushSeries" />
    </div>
  </div>
</template>

<script>
// import { createDownload } from '@/utils'
import { queryEditProFormData, queryEditProData, submitEditProData,
  changeDetailState, submitEditFormData, delDetailTableData,
  putDetailTableData, getProgramData } from '@/api/marketConstruction'
import { getDictByPatchType } from '@/api/dataDict'
import { getUserInfo } from '@/utils/auth'
import StyleDialog from './component/styleDialog.vue'
export default {
  name: 'AddFinishedPlan',
  components: { StyleDialog },
  props: {
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      handleSearchFilters: [], // 手动搜索条件
      searchConfig: [
        { label: '所属专区', prop: 'styleName', type: 'text', placeholder: '', filter: true },
        {
          label: '启用状态',
          prop: 'enable',
          type: 'radio',
          value: '',
          placeholder: '',
          config: {
            selectData: [
              { label: '全部', value: '' },
              { label: '启用', value: '1' },
              { label: '停用', value: '0' }
            ]
          }
        }
      ],
      showPageFlag: true,
      isEditTable: false,
      isEditForm: false,
      loading: false,
      loadingText: '',
      exportVisible: false,
      importVisible: false,
      flag: '',
      showSeriesDlg: false,
      tableLoading: false,
      tableData: [],
      tableInfo: {
        currentPage: 1,
        total: '',
        rows: 10
      },
      jumpPage: '',
      allTotal: 0,
      otherFilters: [],
      selectedRows: [],
      UploadFile: '',
      // assortSeries: [],
      booleansList: [
        { dictCode: 1, dictName: '是' },
        { dictCode: 0, dictName: '否' }
      ],
      enableList: [
        { dictCode: 1, dictName: '启用' },
        { dictCode: 0, dictName: '停用' }
      ],
      cityLevelList: [],
      adviceCityLevel: [],
      formData: {
        areaCode: 'Q015'
      },
      oldFormInfo: {},
      rules: {
        configPlan: [{ required: true, message: '请选择所属方案' }],
        configSpace: [{ required: true, message: '请选择所属空间' }]
      },
      spaceConfig: {
        title: '所属空间',
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configSpace/page`,
        setting: [
          {
            prop: 'spaceCode',
            title: '编码'
          },
          {
            prop: 'spaceName',
            title: '名称'
          }
        ],
        filtersRaw: [{ 'id': 'enable', 'property': 'enable', 'operator': '=', 'value': '1' },
          { 'id': 'areaCode', 'property': 'areaCode', 'operator': '=', 'value': 'Q015' }]
      },
      planConfig: {
        title: '所属方案',
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configProgramDetail/page`,
        setting: [
          {
            prop: 'programCode',
            title: '编码'
          },
          {
            prop: 'programName',
            title: '名称'
          }
        ],
        filtersRaw: [{ 'id': 'enable', 'property': 'enable', 'operator': '=', 'value': '1' },
          { 'id': 'areaCode', 'property': 'areaCode', 'operator': '=', 'value': 'Q015' }]
      }
    }
  },
  computed: {
    // 选中行id
    selectedIds() {
      return this.selectedRows.map(row => {
        return row.seriesCode
      })
    },
    exportConfig() {
      return [{
        code: 'export',
        name: '套房方案配置',
        dataMethod: 'post',
        dataApi: `/slm-admin/api/v1/configProgramSeries/exportProduct?id=${this.detailData.id}&type=0`,
        selectedRows: this.selectedRows,
        paramsRaw: {},
        filtersRaw: [],
        queryField: 'id'
      },
      {
        code: 'exportTemplate',
        name: '套房方案配置模板',
        async: false,
        templateMethod: 'post',
        templateApi: `/slm-admin/api/v1/configProgramSeries/exportProduct?id=${this.detailData.id}&type=1`
      }]
    },
    fileImportConfig() {
      return [{
        code: 'importNew',
        name: '新增套房方案配置',
        async: false,
        apiUrl: `/slm-admin/api/v1/configProgramSeries/importProduct?id=${this.detailData.id}&type=1`
      },
      {
        code: 'importUpdate',
        name: '修改套房方案配置',
        async: false,
        apiUrl: `/slm-admin/api/v1/configProgramSeries/importProduct?id=${this.detailData.id}&type=0`
      }]
    }
  },
  async created() {
    this.getDictByPatchTypeAll(['CITY_LEVEL']).then(res => {
      this.cityLevelList = res.CITY_LEVEL
    })
    const { userName } = getUserInfo()
    if (this.detailData.id) {
      this.formData.id = this.detailData.id
      this.flag = this.detailData.flag
      await this.getFormData()
      await this.getTableData(1, 10, false)
      if (this.flag !== 'detail') {
        this.formData.lastUpdateBy = userName
      }
    } else {
      this.formData.createBy = userName
    }
  },
  activated() {},
  methods: {
    // 清空搜索数据
    clearSearch() {
    },
    // 获取搜索条件
    handleSearch(data) {
      this.handleSearchFilters = [...data.filtersRaw]
      this.getTableData(1, 10, false)
    },
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    formaterArr(dictList, str) {
      if (!str || !str.length) return
      let list = []
      if (typeof (str) === 'string') {
        list = str.split(',')
      } else {
        list = str
      }
      const arr = []
      dictList.forEach((item) => {
        const flag = list.some(v => v === item.dictCode)
        if (flag) {
          arr.push(item.dictName)
        }
      })
      return arr.toString()
    },
    convertDataFormat(str) {
      if (!str || !str.length) return
      const arr = str.split(',')
      return arr
    },
    // 多选框是否可选
    selectable(row) {
      if (!this.showPageFlag) {
        if (row.id) {
          return false
        }
        return true
      }
      return true
    },
    // 获取表单数据
    async getFormData() {
      this.loading = true
      this.loadingText = '加载中'
      await queryEditProFormData(this.formData.id).then(res => {
        if (res.success && res.data) {
          this.formData = res.data
        }
        this.loading = false
        this.loadingText = ''
      }).catch(() => {
        this.loading = false
        this.loadingText = ''
      })
    },
    // 获取表格数据
    async getTableData(page, rows, onlyCountFlag) {
      this.tableLoading = true
      const otherFilter = [...this.handleSearchFilters, { 'id': 'configProgramProductId', 'property': 'configProgramProductId', 'operator': '=', 'value': this.formData.id }]
      const dataForm = new FormData()
      dataForm.append('page', page)
      dataForm.append('rows', rows)
      dataForm.append('onlyCountFlag', onlyCountFlag)
      dataForm.append('filtersRaw', JSON.stringify(otherFilter))
      await queryEditProData(dataForm).then(res => {
        if (res.success && res.data && res.data.records) {
          // this.formData = res.data
          this.tableData = []
          if (res.data.records.length) {
            if (!onlyCountFlag) {
              this.tableData = this.formaterTable(res.data.records)
              this.tableData.forEach(item => {
                this.$set(item, 'editFlag', false)
              })
              this.tableInfo.total = res.data.total
              this.tableInfo.currentPage = res.data.page
              if (this.tableInfo.total <= page * rows) {
                this.allTotal = this.tableInfo.total
              } else {
                this.allTotal = 0
              }
            } else {
              this.allTotal = res.data.total
              this.tableInfo.total = res.data.total
              this.tableInfo.currentPage = res.data.page
            }
          }
        }
        this.tableLoading = false
        this.showPageFlag = true
        this.isEditTable = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 设置产品系列
    formaterTable(data) {
      if (!data || !data.length) return []
      data.forEach(item => {
        const seriesConfig = {
          title: '产品系列',
          interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configSeries/page`,
          setting: [{ prop: 'seriesCode', title: '编码' },
            { prop: 'seriesName', title: '名称' },
            { prop: 'typeName', title: '类型' }],
          filtersRaw: [{ 'id': 'bigStyleName', 'property': 'bigStyleName', 'operator': '=', 'value': item.styleName },
            { 'id': 'isPartakeSpread', 'property': 'isPartakeSpread', 'operator': '=', 'value': 1 }]
        }
        const customizedSeriesConfig = {
          title: '配套定制系列',
          interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configSeries/page`,
          setting: [{ prop: 'seriesCode', title: '编码' },
            { prop: 'seriesName', title: '名称' },
            { prop: 'typeName', title: '类型' }],
          filtersRaw: [{ 'id': 'bigStyleName', 'property': 'bigStyleName', 'operator': '=', 'value': item.styleName },
            { 'id': 'isPartakeSpread', 'property': 'isPartakeSpread', 'operator': '=', 'value': 1 },
            { 'id': 'typeCode', 'property': 'typeCode', 'operator': '=', 'value': '8' }]
        }
        const cupboardSeriesConfig = {
          title: '配套橱柜系列',
          interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configSeries/page`,
          setting: [{ prop: 'seriesCode', title: '编码' },
            { prop: 'seriesName', title: '名称' },
            { prop: 'typeName', title: '类型' }],
          filtersRaw: [{ 'id': 'bigStyleName', 'property': 'bigStyleName', 'operator': '=', 'value': item.styleName },
            { 'id': 'isPartakeSpread', 'property': 'isPartakeSpread', 'operator': '=', 'value': 1 },
            { 'id': 'typeCode', 'property': 'typeCode', 'operator': '=', 'value': '6' }]
        }
        const series = [{ label: item.seriesName, value: item.configSeriesId }]
        let customizedSeries = [{ label: item.assortCustomizedSeriesName, value: item.assortCustomizedSeriesCode }]
        let cupboardSeries = [{ label: item.assortCupboardSeriesName, value: item.assortCupboardSeriesCode }]
        if (!item.assortCustomizedSeriesCode) {
          customizedSeries = []
        }
        if (!item.assortCupboardSeriesCode) {
          cupboardSeries = []
        }
        this.$set(item, 'series', series)
        this.$set(item, 'seriesConfig', seriesConfig)
        this.$set(item, 'customizedSeries', customizedSeries)
        this.$set(item, 'customizedSeriesConfig', customizedSeriesConfig)
        this.$set(item, 'cupboardSeries', cupboardSeries)
        this.$set(item, 'cupboardSeriesConfig', cupboardSeriesConfig)
      })
      return data
    },
    // 获取区域说明
    async getProAreaData() {
      // this.tableLoading = true
      const otherFilter = [{ 'id': 'configProgramId', 'property': 'configProgramId', 'operator': '=', 'value': this.formData.configProgramId }]
      const dataForm = new FormData()
      dataForm.append('onlyCountFlag', false)
      // dataForm.append('sort', 'areaCode')
      // dataForm.append('order', 'ASC')
      dataForm.append('filtersRaw', JSON.stringify(otherFilter))
      await getProgramData(dataForm).then(res => {
        if (res.success && res.data && res.data.records) {
          const arr = res.data.records.filter(item => item.areaCode === 'Q014')
          this.formData.areaDesc = arr[0].areaDesc
        }
      }).catch(() => {
        this.loading = false
      })
    },
    // 切换配套系列
    assortSeriesChange(row) {
      row.assortCustomizedSeriesName = row.assortSeries[0].seriesName
      row.assortCustomizedSeriesCode = row.assortSeries[0].seriesCode
    },
    // 获取因子组合编码集合，作为弹框过滤条件
    getOtherFilter(data) {
      if (data && data.length > 0) {
        const code = data.map(item => item.styleName).join()
        this.otherFilters = [{ id: 'styleName', property: 'styleName', value: `[${code}]`, operator: 'not in' }]
      } else {
        this.otherFilters = []
      }
    },
    // 选择方案
    planChange(row) {
      if (row && row.length) {
        this.formData.configProgramId = row[0].configProgramId
        this.formData.areaName = row[0].areaName
        this.formData.areaDesc = row[0].areaDesc
        this.formData.areaCode = row[0].areaCode
      } else {
        this.formData.configProgramId = ''
      }
    },
    // 选择空间
    spaceChange(row) {
      this.formData.configSpaceId = row[0].id
    },
    // 编辑表单
    handleEditForm() {
      this.oldFormInfo = JSON.parse(JSON.stringify(this.formData))
      const plan = [{ label: this.oldFormInfo.programName, value: this.oldFormInfo.configProgramId }]
      const space = [{ label: this.oldFormInfo.spaceName, value: this.oldFormInfo.configSpaceId }]
      this.$set(this.formData, 'configPlan', plan)
      this.$set(this.formData, 'configSpace', space)
      this.isEditForm = true
    },
    // 取消编辑表单
    cancel() {
      this.formData = JSON.parse(JSON.stringify(this.oldFormInfo))
      this.isEditForm = false
      this.$refs.refForm.clearValidate()
    },
    // 编辑表格数据
    editSerise() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择【编辑】项')
        return
      }
      this.selectedRows.forEach(item => {
        item.editFlag = true
        item.addFlag = false
        const assortSeries = [{ label: item.assortCustomizedSeriesName, value: item.assortCustomizedSeriesCode }]
        const tmpArr = this.convertDataFormat(item.adviceCityLevel)
        this.$set(item, 'assortSeries', assortSeries)
        this.$set(item, 'cityLevel', tmpArr)
      })
      this.isEditTable = true
      this.showPageFlag = false
    },
    // 选择系列
    seriesChange(row, index) {
      if (!row.series.length) {
        row.configSeriesId = ''
        row.seriesName = ''
        return
      }
      const seriesCodeArr = JSON.parse(JSON.stringify(row.series))
      const oldModelIndex = row.series.findIndex(item => item.id === row.configSeriesId)
      const oldModel = row.series.filter(item => item.id === row.configSeriesId)
      if (oldModelIndex !== -1) {
        seriesCodeArr.splice(oldModelIndex, 1)
      }
      // let tmpArr = []
      const tableArr = []
      seriesCodeArr.forEach(model => {
        const obj = {
          areaCode: 'Q015',
          configProgramProductId: this.formData.id,
          configStyleId: row.configStyleId,
          styleCode: row.styleCode,
          styleName: row.styleName,
          seriesName: model.seriesName,
          configSeriesId: model.id,
          adviceArea: row.adviceArea,
          seriesDesc: row.seriesDesc,
          isMustUp: row.isMustUp,
          editFlag: true,
          addFlag: row.addFlag,
          series: [{ label: model.seriesName, value: model.id }]
        }
        tableArr.push(obj)
      })
      const tmpArr = this.formaterTable(tableArr)
      // tmpArr.forEach(item => {
      //   const seriesConfig = {
      //     title: '产品系列',
      //     interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configSeries/page`,
      //     setting: [{ prop: 'seriesCode', title: '编码' },
      //       { prop: 'seriesName', title: '名称' }],
      //     filtersRaw: [{ 'id': 'bigStyleName', 'property': 'bigStyleName', 'operator': '=', 'value': item.styleName }]
      //   }
      //   const series = [{ label: item.seriesName, value: item.configSeriesId }]
      //   this.$set(item, 'series', series)
      //   this.$set(item, 'seriesConfig', seriesConfig)
      // })
      console.log('tmpArr', tmpArr)
      let arr1 = []
      let arr2 = []
      arr1 = this.tableData.filter((row, rowIndex) => {
        const dataIndex = tmpArr.findIndex(v => (v.configStyleId === row.configStyleId) && (v.configSeriesId && (v.configSeriesId === row.configSeriesId)))
        return dataIndex !== -1
      })
      arr2 = tmpArr.filter(row => {
        const index = this.tableData.findIndex(v => (v.configStyleId === row.configStyleId) && (v.configSeriesId && (v.configSeriesId === row.configSeriesId)))
        return index === -1
      })
      console.log('arr1', arr1)
      console.log('arr2', arr2)
      if (arr1.length) {
        const msgArr = arr1.map(item => item.seriesName)
        this.$message.warning(`专区${row.styleName}对应的产品系列${msgArr.toString()}已存在，请重新选择`)
        if (!arr2.length) {
          row.series = []
          row.seriesName = ''
          row.configSeriesId = ''
        }
      }
      if (oldModel.length) {
        const obj = {
          id: row.id,
          areaCode: 'Q015',
          configProgramProductId: this.formData.id,
          configStyleId: row.configStyleId,
          styleCode: row.styleCode,
          styleName: row.styleName,
          seriesName: oldModel[0].seriesName,
          configSeriesId: oldModel[0].id,
          seriesConfig: row.seriesConfig,
          customizedSeriesConfig: row.customizedSeriesConfig,
          cupboardSeriesConfig: row.cupboardSeriesConfig,
          adviceArea: row.adviceArea,
          seriesDesc: row.seriesDesc,
          isMustUp: row.isMustUp,
          editFlag: true,
          addFlag: row.addFlag,
          series: [{ label: oldModel[0].seriesName, value: oldModel[0].configSeriesId }]
        }
        this.$set(this.tableData, index, obj)
      }
      if (arr2.length) {
        if (oldModel.length) {
          arr2.forEach(a => {
            this.tableData.splice(index, 0, a)
          })
        } else {
          if (!row.configSeriesId) {
            arr2[0].id = row.id
          }
          this.$set(this.tableData, index, arr2[0])
          arr2.splice(0, 1)
          if (arr2.length) {
            arr2.forEach(a => {
              this.tableData.splice(index, 0, a)
            })
          }
        }
      }
    },
    // 选择配套定制系列
    customizedSeriesChange(row) {
      console.log(row)
      if (row && row.customizedSeries.length) {
        row.assortCustomizedSeriesName = row.customizedSeries.map(v => v.seriesName).join(',')
        row.assortCustomizedSeriesCode = row.customizedSeries.map(v => v.seriesCode).join(',')
      } else {
        row.assortCustomizedSeriesName = ''
        row.assortCustomizedSeriesCode = ''
      }
    },
    // 选择配套橱柜系列
    cupboardSeriesChange(row) {
      if (row && row.cupboardSeries.length) {
        row.assortCupboardSeriesName = row.cupboardSeries.map(v => v.seriesName).join(',')
        row.assortCupboardSeriesCode = row.cupboardSeries.map(v => v.seriesCode).join(',')
      } else {
        row.assortCupboardSeriesName = ''
        row.assortCupboardSeriesCode = ''
      }
    },
    // 新增系列
    addSerise() {
      // this.getOtherFilter(this.tableData)
      this.showSeriesDlg = true
      this.showSaveBtn = false
      this.showPageFlag = false
      this.isEditTable = false
    },
    pushSeries(data) {
      // const arr1 = []
      // const arr2 = []
      // if (this.tableData.length === 0) {
      const dataArr = data.map(item => {
        const obj = {
          areaCode: 'Q015',
          configProgramProductId: this.formData.id,
          configStyleId: item.id,
          styleName: item.styleName,
          styleCode: item.styleCode,
          adviceArea: '',
          seriesName: '',
          seriesCode: '',
          seriesDesc: '',
          series: [],
          isMustUp: 0,
          enable: 1,
          editFlag: true,
          addFlag: true
        }
        return obj
      })
      const tableArr = this.formaterTable(dataArr)
      this.tableData = [...tableArr, ...this.tableData]
    },
    // 导入
    handleImport() {
      this.importVisible = true
    },
    // 导入成功
    handleImportSuccess() {
      this.getTableData(1, 10, false)
    },
    // 导出
    handleExport() {
      this.exportVisible = true
    },
    // 删除
    handleDel() {
      if (this.selectedRows.length < 1) {
        this.$message.warning(`请选择【删除】项`)
        return false
      }
      const arr = this.selectedRows.filter(item => item.id)
      if (!arr.length) {
        this.$confirm('是否确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.selectedRows.length === this.tableData.length) {
            this.selectedRows = []
            this.tableData = []
            this.$refs.refTable.clearSelection()
          } else {
            const tmpData = this.tableData.filter(row => {
              const index = this.selectedRows.findIndex(v => !row.id && (v.configStyleId === row.configStyleId) && (v.configStyleId === row.configStyleId))
              return index === -1
            })
            console.log('tmpData', tmpData)
            this.tableData = tmpData
            this.selectedRows = []
            this.$refs.refTable.clearSelection()
          }
        })
        return
      }
      const flag = this.selectedRows.some(item => item.enable)
      if (flag) {
        this.$message.warning('只能删除启用状态为【停用】的数据')
        return
      }
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableLoading = true
        // this.selectedRows.forEach(item => { item.dr = 1 })
        const ids = this.selectedRows.map(item => item.id)
        delDetailTableData(ids).then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.getTableData(1, 10, false)
          }
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      })
    },
    // 启用:1/停用:0  state停启用状态
    handleChangeStatus(state) {
      if (!this.selectedRows.length) {
        this.$message.warning(`请选择【${state ? '启用' : '停用'}】项`)
        return
      }
      const tmpArr = this.selectedRows.filter(row => row.enable === state)
      if (tmpArr.length > 0) {
        this.$message.warning(`当前所选分类包含${state ? '启用' : '停用'}状态，请勿重复操作`)
        return
      }
      this.$confirm(`此操作将当前所选数据${state ? '启用' : '停用'},是否继续`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableLoading = true
        this.selectedRows.forEach(item => {
          item.enable = state
          item.areaCode = 'Q015'
        })
        changeDetailState(this.selectedRows).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '操作成功',
              type: 'success'
            })
          }
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      })
    },
    // 取消编辑表格
    cancelEdit() {
      this.getTableData(1, this.tableInfo.rows, false)
    },
    // 选中行
    selectionChangeHandle(rows) {
      this.selectedRows = rows
    },
    // 前往第几页
    showEnter(ev) {
      this.jumpPage = ev.srcElement.value
      this.getTotal(this.jumpPage)
    },
    // 获取总数据条数
    newEnter() {
      this.getTotal(this.tableInfo.currentPage)
    },
    // 当操作在非第一页时，跳回第一页
    jumpToFirstPage() {
      this.tableInfo.currentPage = 1 // 不在第一页搜索时，调回第一页显示
      this.jumpPage = 1
      this.allTotal = 0
      this.tableInfo.total = 0
    },
    // 分页，获取下一页数据
    handleCurrentChange(currentPage) {
      if (this.addEditFlag === true) {
        this.$message.warning('当前处于修改状态，请保存或取消后再跳页')
        return false
      }
      this.jumpPage = currentPage
      this.tableInfo.currentPage = currentPage
      this.getTableData(this.tableInfo.currentPage, this.tableInfo.rows, false)
    },
    // 切换页显示条数
    handleSizeChange(size) {
      this.tableInfo.rows = size
      this.jumpToFirstPage()
      this.getTableData(this.tableInfo.currentPage, size, false)
    },

    // 计算当前数据范围 如:1-20
    handlePageRange(size, currentPage) {
      const start = size * (currentPage - 1) + 1
      const end = size * currentPage

      const pageRange = `${start}-${end}`
      return pageRange
    },

    // 获取数据总条数
    getTotal(val) {
      if (this.allTotal !== 0) return
      let page = this.tableInfo.currentPage
      if (val) {
        page = val
      }
      this.getTableData(page, this.tableInfo.rows, true)
    },
    // 返回
    goBack() {
      if (this.isEditForm || !this.showPageFlag) {
        this.$confirm('存在未保存数据，是否确认取消并返回列表界面?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.dialogShow = false
          this.isEditTable = false
          this.clearForm()
          this.$emit('goBack')
        })
      } else {
        this.dialogShow = false
        this.isEditTable = false
        this.clearForm()
        this.$emit('goBack')
      }
    },
    clearForm(done) {
      this.formData = { areaCode: 'Q015' }
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    // 保存表单
    handleSaveInfo() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          this.loadingText = '系统处理中'
          submitEditFormData(this.formData).then(res => {
            if (res.success) {
              this.$message.success('操作成功')
              this.isEditForm = false
              this.getFormData()
            }
            this.loading = false
            this.loadingText = ''
          }).catch(() => {
            this.loading = false
            this.loadingText = ''
          })
        }
      })
    },
    // 去重
    unique(arr, flag) {
      const res = new Map()
      return arr.filter((arr) => !res.has(arr[flag]) && res.set(arr[flag], 1))
    },
    // 保存表格--新增
    saveNewRow() {
      if (this.submiting) return
      if (!this.tableData.length) {
        this.$message.warning('请添加方案配置数据')
        return
      }
      const arr = this.tableData.filter(row => !row.id)
      if (!arr.length) {
        this.$message.warning('不存在未保存数据，请新增后重试')
        return
      }
      const tmpArr = JSON.parse(JSON.stringify(this.tableData))
      const tmp = tmpArr.filter((row, index) => {
        const rowIndex = this.tableData.findIndex((item, itemIndex) => item.configStyleId === row.configStyleId && item.configSeriesId === row.configSeriesId && index !== itemIndex)
        return rowIndex !== -1
      })
      if (tmp.length) {
        const equal = this.unique(tmp, 'configStyleId')
        equal.forEach(item => {
          item.msg = `所属专区【${item.styleName}】，产品系列【${item.seriesName}】存在重复现象，请重新选择`
        })
        const msgArr = equal.map(a => a.msg)
        this.$message({
          dangerouslyUseHTMLString: true,
          message: msgArr.join('<br />'),
          type: 'warning'
        })
        return
      }
      this.loading = true
      this.loadingText = '系统处理中'
      this.submiting = true
      submitEditProData(arr).then(res => {
        this.submiting = false
        if (res.success === 1) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.$nextTick(() => {
            this.getTableData(1, 10, false)
          })
        }
        this.loading = false
        this.loadingText = ''
      }).catch(() => {
        this.submiting = false
        this.loading = false
        this.loadingText = ''
      })
    },
    // 保存表格--修改
    saveEditRow() {
      this.loading = true
      this.loadingText = '系统处理中'
      const arr1 = this.tableData.filter(item => !item.id)
      const arr2 = this.tableData.filter(item => item.id)
      if (arr1.length) {
        submitEditProData(arr1).then(res => {
          this.submiting = false
        }).catch(() => {
          this.$message({
            message: '新增失败',
            type: 'success'
          })
          this.submiting = false
          this.loading = false
          this.loadingText = ''
        })
      }
      putDetailTableData(arr2).then(res => {
        if (res.success) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.getTableData(1, 10, false)
        }
        this.loading = false
        this.loadingText = ''
      }).catch(() => {
        this.loading = false
        this.loadingText = ''
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.top-btn-group{
  text-align: right;
  margin-bottom: 20px;
}
.btn-group{
  display: flex;
}
.foot-info{
  margin-top: 10px;
}
.but20{ margin-bottom: 20px;}
.el-breadcrumb__inner,.btn-green{
    color: #3DC094;
}
/deep/ .el-breadcrumb__inner{
  color: $qup-color-primary;
}

</style-dialog>
